package com.vitaf.cash.app.ui.fragment

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.graphics.toColorInt
import com.vitaf.cash.app.R
import com.vitaf.cash.app.common.VitafComFmtV2
import com.vitaf.cash.app.configs.GombeCreditApiPath
import com.vitaf.cash.app.configs.GombeCreditApiUrl
import com.vitaf.cash.app.configs.GombeCreditApiUrl.addCommonParams
import com.vitaf.cash.app.databinding.DataBindingHelper
import com.vitaf.cash.app.databinding.FragmentHomeLimitBinding
import com.vitaf.cash.app.event.VitafEventData
import com.vitaf.cash.app.event.VitafEventPointType
import com.vitaf.cash.app.event.room.VitafPointManager
import com.vitaf.cash.app.request.IHttpCallback
import com.vitaf.cash.app.ui.activity.VitafApplyAct
import com.vitaf.cash.app.ui.activity.VitafPermissionsAct
import com.vitaf.cash.app.ui.activity.VitafProcessStepsAct
import com.vitaf.cash.app.ui.dialog.VitafLimitIncreasedDlog
import com.vitaf.cash.app.utils.SpannableStringUtil
import com.vitaf.cash.app.utils.ext.addEndRegex
import com.vitaf.cash.app.utils.helper.VitafProcessHp
import com.vitaf.cash.app.utils.log.VitafLog
import com.vitaf.cash.app.utils.shared.VitafSharedHp
import com.vitaf.cash.app.utils.shared.VitafSharedKey
import org.json.JSONObject
import pub.devrel.easypermissions.EasyPermissions
import java.math.BigDecimal

/**
 * VitafCash
 * @Author wwdeng
 * @CreateTime: 2024/12/10 14:53
 * @Annotation：主页
 */
class HomeLimitFragment : VitafComFmtV2() {
    private var _binding: FragmentHomeLimitBinding? = null

    private var viewModel = DataBindingHelper.createModel()

    public override val pageName: String = "Home_Limit_Page"

    override fun createVitafContentView(inflater: LayoutInflater): View? {
        _binding = FragmentHomeLimitBinding.inflate(inflater)
        return _binding?.root
    }

    override fun initializeVitafViews() {
        val binding = _binding ?: return
        // 设置 DataBinding
        binding.limitFragment = this
        binding.lifecycleOwner = viewLifecycleOwner
        binding.model = viewModel
        binding.homePageRefreshLayout.setColorSchemeResources(R.color.theme, R.color.black)
        showLimitPageAnnualInterestText()
    }

    override fun setupVitafEventListeners() {
        _binding?.homePageRefreshLayout?.setOnRefreshListener {
            onGombeCreditRefreshData()
        }
    }

    override fun loadVitafData() {
        showVitafLoading()
        loadGombeCreditHomeLimitAction()
        loadGombeCreditLimitIncreasedAction()
    }

    /**
     * 刷新流程
     */
    private fun onGombeCreditRefreshData(){
        publishEventData(VitafEventData(VitafEventData.TYPE.GOMBECREDIT_PROCESS_REFRESH))
    }

    /**
     * 设置年利率
     */
    private fun showLimitPageAnnualInterestText(){
        val binding = _binding ?: return
//        val typeface = ResourcesCompat.getFont(requireContext(), R.font.roboto_black)
        val interestText = String.format(getString(R.string.home_limit_annual_interest), getString(R.string.home_limit_annual_interest_rate))
        val spannableText = SpannableStringUtil.create()
            .setText(interestText)
            .setKey(getString(R.string.home_limit_annual_interest_rate))
            .setColor("#FFFFFFFF".toColorInt())
            .setBold()
            .complete()
            .build()

        binding.homeLimitAnnualInterestText.text = spannableText
    }

    /**
     * 点击申贷
     */
    fun onClickLimitApply(){
        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.LOAN_APPLY,pageName)
        // TODO: 首页点申请 需上报所有埋点
        VitafPointManager.getInstance().manualReport()

        checkGombeCreditPermissions()
    }

    /**
     * 显示额度
     */
    private fun showGombeCreditHomeLimit(data: JSONObject?){
        data?.let {
            data.put("amount",data.optString("amount").addEndRegex())
            viewModel.setJson(data)
        }
    }

    /**
     * 权限声明列表
     */
    private val permissionResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                var isNext = false
                result.data?.let { bundle ->
                    val isAgree = bundle.getBooleanExtra("isPermissionAgree",false)
                    VitafLog.e(">>>>>>>>>permission is agree ：$isAgree")
                    //同意，校验权限 进行下一步
                    isNext = if (isAgree){
                        true
                    } else {//拒绝，
                        //是否是广告渠道
                        val isAdSource = VitafSharedHp.takeGombeCreditSharedBoolean(VitafSharedKey.GOMBECREDIT_IS_ADSOURCE)
                        //非广告渠道才继续校验进行下一步
                        !isAdSource
                    }
                }
                if (isNext){
                    checkGombeCreditPermissions()
                }
            }
        }
    }

    /**
     * 检查权限
     */
    private fun checkGombeCreditPermissions(){
        //权限页操作状态 : 0未操作  1已同意  -1拒绝
        val permissionStatus = VitafSharedHp.takeGombeCreditSharedInt(VitafSharedKey.GOMBECREDIT_PERMISSIONS_STATUS)
        //权限列表未操作 -> 进入权限列表
        if (permissionStatus == 0){
            showGombeCreditPermissionsPage()
            return
        }
        //是否是广告渠道
        val isAdSource = VitafSharedHp.takeGombeCreditSharedBoolean(VitafSharedKey.GOMBECREDIT_IS_ADSOURCE)
        //广告渠道 && 权限列表未同意 -> 进入权限列表
        if (isAdSource && permissionStatus == -1){
            showGombeCreditPermissionsPage()
            return
        }
        //广告渠道 && 未同意sms权限 -> 进入权限列表
        if (isAdSource && !EasyPermissions.hasPermissions(requireContext(), Manifest.permission.READ_SMS)){
            showGombeCreditPermissionsPage()
            return
        }

        //已同意权限列表 && 已同意SMS权限 -> 上报设备数据
        if (permissionStatus == 1 && EasyPermissions.hasPermissions(requireContext(), Manifest.permission.READ_SMS)){
            //上报所有设备数据
            publishEventData(VitafEventData(VitafEventData.TYPE.GOMBECREDIT_SYC_ALL_DEVICE))
        }

        // 进件信息未完成
        if (VitafProcessHp.takeGombeCreditStepList().isNotEmpty()){
            showGombeCreditProcessStepsPage()
            return
        }

        //权限已全部同意 && 进件信息已完成 - 申贷试算页面
        showGombeCreditApplyPage()
    }

    /**
     * 进入权限列表页面
     */
    private fun showGombeCreditPermissionsPage(){
        val limitAmount = BigDecimal(viewModel.getString("amount","")).stripTrailingZeros().toPlainString()
        val intent = Intent(context, VitafPermissionsAct::class.java)
        intent.putExtra("amount", limitAmount)
        permissionResultLauncher.launch(intent)
    }

    /**
     * 进入填写进件信息页面
     */
    private fun showGombeCreditProcessStepsPage(){
        val limitAmount = BigDecimal(viewModel.getString("amount","")).stripTrailingZeros().toPlainString()
        VitafProcessStepsAct.start(requireContext(),limitAmount)
    }

    /**
     * 进入申贷页面
     */
    private fun showGombeCreditApplyPage(){
        VitafApplyAct.start(requireContext())
    }

    /**
     * 额度增加提示
     */
    private fun showGombeCreditLimitIncreasedDialog(data: JSONObject){
        val dialog = VitafLimitIncreasedDlog(requireContext(),data.optString("product"),object : VitafLimitIncreasedDlog.IDialogCallback{
            override fun onClick(view: View?) {
                //申请
                onClickLimitApply()
            }
        })
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
        dialog.showGombeCreditLimitIncreasedData(data)
    }

    override fun onVitafPublishEvent(event: VitafEventData) {
        super.onVitafPublishEvent(event)
        when (event.eventType) {
            VitafEventData.TYPE.GOMBECREDIT_DATA_REFRESH,
            VitafEventData.TYPE.GOMBECREDIT_PROCESS_REFRESHED -> { //刷新流程完成
                //待还款
                val isRepay = VitafProcessHp.isGombeCreditRepay()
                //审核中 || 放款中 || 已拒绝
                val isReviewing = VitafProcessHp.isGombeCreditReviewing()
                val isDisbursing = VitafProcessHp.isGombeCreditDisbursing()
                val isRejected = VitafProcessHp.isGombeCreditRejected()
                if (isRepay or isReviewing or isDisbursing or isRejected){
                    return
                }

                loadGombeCreditHomeLimitAction()
                loadGombeCreditLimitIncreasedAction()
            }

            VitafEventData.TYPE.GOMBECREDIT_ORDER_REFRESHED -> {//订单刷新完成
            }

            VitafEventData.TYPE.GOMBECREDIT_SHOW_AUTHENTICATION -> {
            }
            else -> {

            }
        }
    }

    /**
     * 获取显示额度
     */
    private fun loadGombeCreditHomeLimitAction(){
        val params = JSONObject()
            .addCommonParams()
            .apply {
                put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_LIMIT_PATH)
            }
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                val limitArray = obj?.optJSONArray("limit")
                limitArray?.let {
                    if (it.length() > 0){
                        val limitObj = it.optJSONObject(0)
                        showGombeCreditHomeLimit(limitObj)
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideVitafLoading()
            }
        })
    }

    /**
     * 加载产品额度是否增加
     */
    private fun loadGombeCreditLimitIncreasedAction(){
        val params = JSONObject()
            .addCommonParams()
            .apply {
                put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_LIMIT_UP_PATH)
            }
        //todo 测试提额dialog
//        params.put("selectAmount","2000")
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                obj?.let {
                    if (it.optString("openFlag") == "YES"){
                        showGombeCreditLimitIncreasedDialog(it)
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideVitafLoading()
            }
        })
    }

    override fun hideVitafLoading() {
        super.hideVitafLoading()
        _binding?.homePageRefreshLayout?.isRefreshing = false
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}